package hflyeer.o2o.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

public class ImageUtils {
	private static String basePath = PathUtils.getImageBasePath();
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");

	// 日志
	private static final Logger logger = LoggerFactory.getLogger(ImageUtils.class);

	/**
	 * 将CommonsMultipartFile转化为File
	 * 
	 * @param file
	 * @return
	 */
	public static File transferCommonsMultipartFileToFile(MultipartFile file) {
		File newFile = new File(file.getOriginalFilename());
		try {
			file.transferTo(newFile);
		} catch (IllegalStateException | IOException e) {
			logger.error("CommonsMultipartFile转化为File错误:"+ e.toString());
			e.printStackTrace();
		}
		return newFile;
	}

	/**
	 * 图片添加水印
	 * 
	 * @param file       文件原来路径
	 * @param targetPath 存放目标路径 末尾需要加入/
	 * @return
	 */
	public static String thumbnails(File file, String targetPath) {
		String realFileName = getRandomFileName();
		String extension = getFileExison(file.getName());
		createDirectory(targetPath);
		String relativePath = targetPath + realFileName + extension;
		logger.debug("文件相对路径："+ relativePath);
		logger.debug("文件绝对路径："+basePath + relativePath);
		try {
			Thumbnails.of(file).size(1920, 1080)
					.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "mark/watermark.jpg")), 0.5f)
					.outputQuality(0.8f).toFile(basePath + relativePath);
		} catch (IOException e) {
			logger.error("添加水印错误:"+ e.toString());
			e.printStackTrace();
		}
		return relativePath;
	}

	/**
	 * 创建目录
	 * 
	 * @param targetPath
	 */
	private static void createDirectory(String targetPath) {
		File target = new File(basePath + targetPath);
		if (!target.exists()) {
			target.mkdirs();
		}
	}

	/**
	 * 获取文件后缀名
	 * 
	 * @return
	 */
	private static String getFileExison(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}

	/**
	 * 随即生成文件名称 年月日时分秒+5为随即数
	 * 
	 * @return
	 */
	private static String getRandomFileName() {
		int r = (int) (Math.random() * (99999 - 10000) + 10000);
		return sdf.format(new Date()) + r;
	}

}
